package cn.tedu.school.portal.controller;


import cn.tedu.school.portal.model.User;
import cn.tedu.school.portal.service.IUserService;
import cn.tedu.school.portal.service.ex.ParameterValidationException;
import cn.tedu.school.portal.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2020-07-23
 */
@RestController
@Slf4j
@RequestMapping("/api/v1/user")
public class UserController {
    @Autowired
    private IUserService userService;
    //http://localhost:8080/api/v1/user/student/register?studentId=JSD1911&username=控制层测试&password=123456&classId=1
    @RequestMapping("/student/register")
    public R<Void> studentRegister(@Validated User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String errorMessage = bindingResult.getFieldError().getDefaultMessage();
            log.debug("errorMessage>{}", errorMessage);
            throw new ParameterValidationException(errorMessage);
        }
        /*通过GlobalException类统一处理异常*/
        userService.registerStudent(user);
        return R.ok();
    }

    //http://localhost:8080/api/v1/user/student/login?studentId=JSD200313&password=8516935
    @RequestMapping("/student/login")
    public R<User> login(String studentId, String password, HttpSession session){
        System.err.println("UserController.login()");
        System.err.println("\t客户端提交的数据：usenrame=" + studentId);
        System.err.println("\t客户端提交的数据：password=" + password);
        User data = userService.login(studentId, password);
        System.err.println("\t登录成功：user=" + data);
        session.setAttribute("uid", data.getId());
        session.setAttribute("username", data.getUsername());
        return R.ok(data);
    }


    @RequestMapping("/student/changePassword")
    public R<Void> changePassword(Integer userId,String password){
        userService.changePassword(userId,password);
        return R.ok();
    }





}
